from datetime import timedelta

from flask import jsonify

from APP import db
from APP.models.alert_list import alert_list
from flask import Blueprint



danger_charts_bp = Blueprint('danger_charts', __name__)

@danger_charts_bp.route('/dangerCharts/<int:id>')
def show_test(id):
    data = db.session.query(alert_list).filter(alert_list.id == id).first()
    if not data:
        return jsonify({
            "message": "未找到对应数据",
            "code": 404
        }), 404
    time_window = timedelta(minutes=2)
    start_time = data.time - time_window
    end_time = data.time + time_window
    danger_data = db.session.query(alert_list).filter(
        alert_list.time.between(start_time, end_time)
    ).all()

    # 使用字典去重并保持时间与值的对应关系
    time_value_map = {}
    for item in danger_data:
        time_str = item.time.strftime("%H:%M:%S")
        time_value_map[time_str] = item.value
    time_value_map[data.time.strftime("%H:%M:%S")] = data.value
    # 将去重后的时间排序
    sorted_times = sorted(time_value_map.keys())
    timedata = sorted_times
    valuedata = [time_value_map[t] for t in sorted_times]

    # 处理危险时段数据
    begin_time = data.time.strftime("%H:%M:%S")
    begin_index = timedata.index(begin_time)
    try:
        end_time = timedata[begin_index + 2]
    except:
        end_time = begin_time

    danger_date = [{
        "name": data.title,
        "begin": begin_time,
        "end": end_time
    }]
    if not danger_data:
        return jsonify({
            "message": "未找到对应数据",
            "code": 404
        }), 404

    return jsonify({
        "message": "Success",
        "code": 200,
        "data": {
                "id": id,
                "dangerChart01": {
                    "timedata": timedata,
                    "valuedata": valuedata,
                },
                "dangerdata": danger_date,
                "worknote": []
        }
    })
